<?php

namespace scaffold\auth;

use think\facade\Cache;

/**
 * token缓存类
 * @author edward <edward@localhost.com>
 */
class Token
{
    /**
     * 索引值
     * @var string
     */
    protected $index;

    /**
     * token 标识
     * @var string
     */
    protected $token = '';

    /**
     * 键值前缀
     * @var string
     */
    protected $prefic = '';

    /**
     * 过期时效
     * @var integer
     */
    protected $expire = 300;

    /**
     * 构造函数
     * @author edward edward@localhost.com
     * @DateTime 2020-07-20
     * @version  1.0.0.0
     *
     * @param    string     $prefic 键值前缀
     * @param    integer    $expire 过期时效
     */
    public function __construct($prefic = '', $expire = 300)
    {
        $this->prefic = $prefic;
        $this->expire = $expire;
    }

    /**
     * 记入索引获取token
     * @author edward edward@localhost.com
     * @DateTime 2020-07-20
     * @version  1.0.0.0
     *
     * @param    string     $index 索引值
     * @return   string            token
     */
    public function signIn($index)
    {
        $index && $this->index = $index;
        $this->clear($this->index);
        $this->token = $this->randToken();
        Cache::set("{$this->prefic}token:{$this->token}", $this->index, $this->expire);
        Cache::set("{$this->prefic}index:{$this->index}", $this->token, $this->expire);
        return $this->token;
    }

    /**
     * 清除缓存
     * @author edward edward@localhost.com
     * @DateTime 2020-07-20
     * @version  1.0.0.0
     *
     * @param    string     $index 索引
     * @return   none
     */
    public function clear($index)
    {
        $token = $this->getToken($index);
        Cache::rm($this->prefic . 'token:' . $token);
        Cache::rm($this->prefic . 'index:' . $index);
    }

    /**
     * 获取索引值
     * @author edward edward@localhost.com
     * @DateTime 2020-07-20
     * @version  1.0.0.0
     *
     * @param    string     $token token值
     * @return   string            索引值
     */
    public function getIndex($token)
    {
        return Cache::get($this->prefic . 'token:' . $token);
    }

    /**
     * 获取token
     * @author edward edward@localhost.com
     * @DateTime 2020-07-20
     * @version  1.0.0.0
     *
     * @param    string     $index 索引值
     * @return   string            token值
     */
    public function getToken($index)
    {
        return Cache::get($this->prefic . 'index:' . $index);
    }

    /**
     * 随机token
     * @param  integer $len 生成长度
     * @return string
     */
    private function randToken($len = 32)
    {
        return substr(md5(uniqid(microtime(true), true)), 0, $len);
    }

}
